//
//  CountdownButton.swift
//  JJToolSwift
//
//  Created by heihei on 2024/5/26.
//

import UIKit

public enum CountdownState: Int {
    case normal = 0
    case countdown
    case reget
}

public class CountdownButton: UIButton {

    /// 按钮状态
    private var countState: CountdownState = .normal {
        didSet {
            isEnabled = countState != .countdown
            if countState == .countdown {
                if timer == nil {
                    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
                    timer?.fire()
                }
            } else {
                if timer != nil {
                    timer?.invalidate()
                    timer = nil
                }
                if countState == .reget {
                    self.setTitle("重新获取", for: [])
                }
            }
        }
    }

    /// 计时器
    private var timer: Timer?

    /// 计数
    private var leftCount: Int = 10
    
    override open func awakeFromNib() {
        super.awakeFromNib()
        reset()
    }
    
    /// 重置
    func reset() {
        countState = .normal
    }

    /// 开始
    public func start(_ count: Int = 60) {
        leftCount = count
        countState = .countdown
    }

    /// 结束
    public func stop() {
        countState = .reget
    }

    /// 定时器
    @objc private func countDown() {
        if leftCount <= 0 {
            stop()
        } else {
            leftCount -= 1
            self.setTitle("\(leftCount)秒", for: [])
        }
    }

}
